import setHours from 'date-fns/setHours';
import differenceInCalendarDays from 'date-fns/differenceInCalendarDays';
import { Component, OnInit } from '@angular/core';
import { AxiosService } from '../../axios.service';
import { DatePipe } from '@angular/common';
import { LocalStorageService } from 'src/app/myService/local-storage.service';
import { DisabledTimeFn, DisabledTimePartial } from "ng-zorro-antd/date-picker/standard-types";

@Component({
  selector: 'app-ruku',
  templateUrl: './ruku.component.html',
  styleUrls: ['./ruku.component.scss'],
  providers: [DatePipe]
})
export class RukuComponent implements OnInit {
  listOfData = []; // 表格数据
  splitJudge = ','; // 逗号隔开19码

  addTime; // 添加时间弹框
  isOkLoadingTime;
  time; // 添加时间值

  searchUnion = ''; // 工联单号筛选框输入的内容
  searchName = ''; // 治具名称筛选框输入的内容
  search19 = ''; // 19码筛选框输入的内容
  listOfDisplayData = []; // 保存筛选之后的数组
  dataArr = []; // 保存筛选前的数组

  addLqzj; // 添加领取治具弹框
  startValue; // 领取时间
  lqsl; // 领取数量
  twoOk; // 确认添加领取治具弹框
  lingqu_time; // 領取時間
  lingqu_count; // 领取数量
  lingquPerson; // 领取人
  lingquTotal; // 已领取的总数
  quatity; // 数量
  ruku_time; // 入庫時間
  lingquUnionorder;

  union_order; // 工单号
  id;

  beizhuRemark;
  ruku_beizhu; // 备注
  rukuRemark; // 添加备注
  isOkLoadingRemark;

  // 日期只能选择今天及以后
  today = new Date();
  timeDefaultValue = setHours(new Date(), 0);

  radioValue = 'All'; // 默认筛选
  style = {
    display: 'block',
    height: '35px',
    width: '130px',
    lineHeight: '35px',
    padding: '0px 15px'
  };

   // 以下数据用于指派工程师后发送邮件
   engineerJobNo = [];
   engineerMail = [];
   mailParamsForSend = {
     "type": '',
     "WorkOrder": "",
     "factory": "",
     "name": "",
     "machine_type": "",
     "quantity": 0,
     "toolway": "",
     "delivery_date": "",
     "emp": [],
     "empAddress":[]
   };

  constructor(
    public axios: AxiosService,
    private datePipe: DatePipe,
    // public activatedRoute: ActivatedRoute,
    private storage: LocalStorageService,
    // private router: Router
  ) { }

  ngOnInit(): void {
    this.getData();
  }

  disabledDate = (current: Date): boolean => {
    // Can not select days before today and today
    return differenceInCalendarDays(current, this.today) < 0;
  };

  // 查询工单信息  { "stage": 7, "stageValue": 1 }
  getData() {
    this.axios.axiosPost('QueryUnionOrder', { "stage": 7, "stageValue": 1 })
      .then((data) => {
        if (data) {
          console.log(data);
          this.listOfData = data['order'];
          console.log(this.listOfData);
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }

  //筛选治具状态
  doingForm() {
    if (this.radioValue === 'All') {
      this.getData();
    } else if (this.radioValue === '待入库') {
      this.axios.axiosPost('QueryUnionOrder', { 'warehouse': 0, 'stage': 7, 'stageValue': 1 })
        .then((data) => {
          if (data) {
            console.log(data);
            this.listOfData = data['order'];
            console.log(this.listOfData);
          }
        })
        .catch((err) => {
          console.log(err);
        })
    } else if (this.radioValue === '待領取') {
      this.axios.axiosPost('QueryUnionOrder', { "warehouse": 1, 'stage': 7, 'stageValue': 1 })
        .then((data) => {
          if (data) {
            console.log(data);
            this.listOfData = data['order'];
            console.log(this.listOfData);
          }
        })
        .catch((err) => {
          console.log(err);
        })
    } else if (this.radioValue === '部分領取') {
      this.axios.axiosPost('QueryUnionOrder', { "warehouse": 2, 'stage': 7, 'stageValue': 1 })
        .then((data) => {
          if (data) {
            console.log(data);
            this.listOfData = data['order'];
            console.log(this.listOfData);
          }
        })
        .catch((err) => {
          console.log(err);
        })
    } else if (this.radioValue === '已領取') {
      this.axios.axiosPost('QueryUnionOrder', { "warehouse": 3, 'stage': 7, 'stageValue': 1 })
        .then((data) => {
          if (data) {
            console.log(data);
            this.listOfData = data['order'];
            console.log(this.listOfData);
          }
        })
        .catch((err) => {
          console.log(err);
        })
    }
  }

  // 显示入库时间弹框
  addDate(item) {
    console.log(item)
    this.union_order = item.union_order;
    this.addTime = true;
    var showTime = new Date();
    let year = showTime.getFullYear();
    let mon = showTime.getMonth() + 1 < 10 ? "0" + (showTime.getMonth() + 1) : showTime.getMonth() + 1;
    let da = showTime.getDate() < 10 ? "0" + showTime.getDate() : showTime.getDate();
    let hour = showTime.getHours() < 10 ? "0" + showTime.getHours() : showTime.getHours();
    let munite = showTime.getMinutes() < 10 ? "0" + showTime.getMinutes() : showTime.getMinutes();
    this.time = year + '/' + mon + '/' + da + ' ' + hour + ':' + munite;
  }
  //取消添加时间
  CancelAddTime() {
    this.addTime = false;
  }
  //确定添加时间
  addTimeOk() {
    this.isOkLoadingTime = true;
    this.addTime = false;
    this.isOkLoadingTime = false;
    console.log(this.time)
    this.axios.axiosPost('UpdateUnionOrder2', { 'unionorder': this.union_order, name1: 'ruku_time', newValue1: this.time })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          console.log(data);
          this.getData();
          this.axios.axiosPost("UpdateUnionOrder2", { 'unionorder': this.union_order, "name1": "stage", "newValue1": 6, "stageValue": 0 }).then((data) => {
            console.log(data, "工单状态修改成功了,取消了当前工单状态")
          })
        }
      })
      .catch((err) => {
        console.log(err)
      })
  }

  // 显示领取治具弹框
  receive(item) {
    this.union_order = item.union_order;
    this.lingqu_time = item.lingqu_time;
    // 获取name
    this.lingquPerson = this.storage.getStorageData('user').name;
    this.ruku_time = item.ruku_time;
    this.quatity = item.quatity;
    this.lingquTotal = item.lingqu_count;
    this.lingquUnionorder = item.union_order;
    if (this.ruku_time !== '') {
      this.addLqzj = true;
    } else {
      alert('入庫時間不能為空');
    }

    // 准备邮件发送的参数
    this.mailParamsForSend.type = 'S6';
    this.mailParamsForSend.WorkOrder = item.union_order;
    this.mailParamsForSend.factory = item.factory;
    this.mailParamsForSend.name = item.name;
    this.mailParamsForSend.machine_type = item.machine_type;
    this.mailParamsForSend.quantity = item.quatity;
    this.mailParamsForSend.delivery_date = item.delivery_date;

    console.log(this.lqsl)
  }
  // 取消
  CancelReceive() {
    this.addLqzj = false;
    this.startValue = '';
    this.lqsl = '';
  }
  // 确认领取治具
  ReceiveOk() {
    if (this.startValue && this.lqsl && this.lingquPerson && Number(this.lqsl) >= 0) {
      this.isOkLoadingTime = true;
      this.addLqzj = false;
      this.twoOk = true;
      this.isOkLoadingTime = false;

    } else {
      alert('領取時間/領取人/領取數量不能為空,領取數量必須大於等於0')
    }
    console.log(this.lingquPerson, this.lingquTotal, this.quatity)
    console.log(this.lqsl)
  }
  // 二次确认 取消
  twoOkCancel() {
    this.twoOk = false;
    this.addLqzj = true;
  }
  // 二次确认 确认
  TwoOk() {

    this.isOkLoadingTime = true;
    this.twoOk = false;
    this.isOkLoadingTime = false;
    console.log(this.lqsl)
    // this.lqsl = Number(this.lingqu_count);
    if (Number(this.lingquTotal) + Number(this.lqsl) <= this.quatity) {
      this.axios.axiosPost('UpdateUnionOrder2', {
        'unionorder': this.union_order,
        name1: 'lingqu_time', newValue1: this.startValue,
        name2: 'lingqu_count', newValue2: Number(this.lqsl) + Number(this.lingquTotal),
        name3: 'lingqu_ren', newValue3: this.lingquPerson,
        name4: "lqsl", newValue4: this.lqsl,
      })
        .then((data) => {
          console.log(data);

          if (data['result'] === 'ok') {
            console.log(this.lqsl)
            console.log(data);
            this.getData();
            this.startValue = '';
            this.lqsl = '';
            // this.axios.axiosPost('AddDeliveryOrder', { 'unionorder': this.union_order, 'quatity': this.lqsl, 'lingqu_ren': this.lingquPerson })
            //   .then((data) => {
            //     console.log(data)
            //     if (data['result'] === 'ok') {
            //       console.log(data);
            //       this.getData();
            //       this.startValue = '';
            //       this.lqsl = '';
            //     }
            //   })
            //   .catch((err) => {
            //     console.log(err);
            //   })

            this.axios.axiosPost('SendEmail', this.mailParamsForSend).then((data) => {
              if (data['result'] === 'ok') {
                console.log("SendEmailSuccessfully!");
              }
            }).finally(() => {
              // 每次指定完毕后，重置数组，避免影响下次指定
              this.engineerJobNo = []
              this.engineerMail = []
            })
          }
        })
        .catch((err) => {
          console.log(err);
        })
    } else {
      alert('領取的數量超過治具數量');
    }
  }
  // 选择日期
  onStartChange(date: Date): void {
    this.startValue = date;
    this.startValue = this.datePipe.transform(this.startValue, 'yyyy-MM-dd HH:mm:ss');
    console.log(this.startValue)
  }

  // 添加备注
  addRemark(item) {
    this.beizhuRemark = true;
    this.rukuRemark = item.ruku_beizhu;
    this.union_order = item.union_order;
  }
  // 取消添加备注
  CancelAddRemark() {
    this.beizhuRemark = false;
  }
  // 确认添加备注
  addRemarkOk() {
    this.isOkLoadingRemark = true;
    this.beizhuRemark = false;
    this.isOkLoadingRemark = false;
    this.axios.axiosPost('UpdateUnionOrder2', { 'unionorder': this.union_order, name1: 'ruku_beizhu', newValue1: this.rukuRemark })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          console.log(data);
          this.getData();
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }

  // 工联单号 筛选的取消按钮
  resetUnion() {
    this.searchUnion = '';
    this.listOfData = this.dataArr;
  }
  // 工联单号 筛选的确认搜索按钮
  searchOkUnion() {
    console.log(this.searchUnion)
    const filterFunc = (item: { union_order: string; }) => {
      return (
        item.union_order.indexOf(this.searchUnion) !== -1
      );
    };
    const data = this.listOfData.filter((item: { union_order: string; }) => filterFunc(item));
    this.listOfDisplayData = data;
    this.dataArr = this.listOfData;
    this.listOfData = this.listOfDisplayData;
    console.log(this.listOfData)
  }

  // 治具名称 筛选的取消按钮
  resetName(): void {
    this.searchName = '';
    this.listOfData = this.dataArr;
  }
  // 治具名称 筛选的确认搜索按钮
  searchOkName(): void {
    console.log(this.searchName)
    const filterFunc = (item: { name: string; }) => {
      return (
        item.name.indexOf(this.searchName) !== -1
      );
    };
    const data = this.listOfData.filter((item: { name: string; }) => filterFunc(item));
    console.log(data)
    this.listOfDisplayData = data;
    this.dataArr = this.listOfData;
    this.listOfData = this.listOfDisplayData;
    console.log(this.listOfData)
  }

  // 19码 筛选的取消按钮
  reset19(): void {
    this.search19 = '';
    this.listOfData = this.dataArr;
  }
  // 19码 筛选的确认搜索按钮
  searchOk19(): void {
    console.log(this.search19)
    const filterFunc = (item: { code19: string; }) => {
      return (
        item.code19.split(',')[0].indexOf(this.search19) !== -1
      );
    };
    const data = this.listOfData.filter((item: { code19: string; }) => filterFunc(item));
    this.listOfDisplayData = data;
    this.dataArr = this.listOfData;
    this.listOfData = this.listOfDisplayData;
    console.log(this.listOfData)
  }


}
